package jim.h.commons;

import java.io.StringReader;
import java.io.StringWriter;
import java.util.ArrayList;
import java.util.List;

import javax.xml.bind.JAXBContext;
import javax.xml.bind.JAXBException;
import javax.xml.bind.Marshaller;
import javax.xml.bind.Unmarshaller;
import javax.xml.bind.annotation.XmlRootElement;

public class TestJaxb {

    public static void main(String[] args) throws JAXBException {
        JAXBContext context = JAXBContext.newInstance(People.class);

        Marshaller marshaller = context.createMarshaller();
        marshaller.setProperty(Marshaller.JAXB_ENCODING, "utf-8");
        marshaller.setProperty(Marshaller.JAXB_FORMATTED_OUTPUT, true);
        marshaller.setProperty(Marshaller.JAXB_FRAGMENT, false);

        People people = new People();
        people.id = "001";
        people.name = "jim";
        people.age = 24;
        people.list = new ArrayList<String>();
        people.list.add("a");

        StringWriter writer = new StringWriter();
        marshaller.marshal(people, writer);
        String xml = writer.getBuffer().toString();
        System.out.println(xml);

        StringReader reader = new StringReader(xml);
        Unmarshaller unmarshaller = context.createUnmarshaller();
        people = (People) unmarshaller.unmarshal(reader);

        System.out.println(people.list);
    }

    @XmlRootElement
    public static class People {

        public String       id;
        public String       name;
        public int          age;
        public List<String> list;
    }
}
